"""
 前置后置操作:初始化操作
"""
import asyncio
from playwright.sync_api import sync_playwright,expect
from Config.URL import *
import allure
import re
from Config.config import *
import json
class Base():
    """
       启动浏览器
    """
    def __init__(self,playwright):
        #self.playwright = sync_playwright().start()
        self.playwright = playwright
        self.browser = playwright.chromium.launch(headless=False)
        self.context = self.browser.new_context(viewport={'width': 1920, 'height': 1080})
        self.page = self.context.new_page()  # 打开一个页面

    def start(self):
        self.playwright = sync_playwright().start()
        self.browser = self.playwright.chromium.launch(headless=False)  # 设置了每步等待时间为3s
        self.context = self.browser.new_context(viewport={'width': 1920, 'height': 1080})
        self.page = self.context.new_page()  # 打开一个页面
    """
        跳转链接
    """
    def goto(self,http):
        self.page.goto(http)

    """
       登录
    """
    def login(self,name,password):
        self.page.get_by_placeholder("请输入用户名").fill(name)
        self.page.get_by_placeholder("请输入密码").fill(password)
        self.page.get_by_role("button", name="登 录").click()
        '''在Python中，可以使用globals()函数和locals()函数来将字符串转换为对应的变量名。globals()函数返回当前模块的全局符号表字典，locals()函数返回当前局部符号表字典。'''

    """
           是否登录成功
        """

    def expect_login(self):
        self.page.wait_for_timeout(2000)
        expect(self.page.locator("#app")).to_contain_text("UAT-环北部湾广西水资源配置工程")

    """
        关闭浏览器
    """
    def close(self):
        self.browser.close()  # 关闭浏览器对象
        #self.playwright.stop()  # 关闭playwright对象释放资源

    """
      截图操作保存到result_image目录下
    """
    def screenshot(self, element, file_name):
        self.page.locator(element).screenshot(path=f"../result_image/{file_name}.png")

    def seturl(self,response):
        try:
            if "viewPorcess/getViewRecord" in response:
                self.httpurl = response
                print("设置流程接口：" + self.httpurl)
        except:
            print("异常设置流程接口：" + self.httpurl)


    def geturl(self):
        try:
            print("获取流程接口：" + self.httpurl)
            return self.httpurl
        except:
            print("异常获取流程接口：" + self.httpurl)

    @allure.step("选择标段")
    def select_bd(self, value):
        self.page.locator("div").filter(has_text=re.compile(r"请选择标段$")).get_by_role("textbox").click()
        self.page.locator("div").filter(has_text=re.compile(r"请选择标段$")).get_by_role("textbox").fill(value)
        self.page.locator("div").filter(has_text=re.compile(r"请选择标段$")).get_by_role("textbox").press("Enter")

    @allure.step("选择所属标段")
    def select_ssbd(self, value):
        self.page.locator("form").filter(has_text=value).get_by_role("textbox").click()
        self.page.locator("form").filter(has_text=value).get_by_role("textbox").fill(value)
        self.page.get_by_text(value).click()

    @allure.step("选择合同")
    def select_ht(self, value):
        self.page.locator("div").filter(has_text=re.compile(r"^请选择合同名称$")).get_by_role("textbox").fill(value)
        self.page.locator("div").filter(has_text=re.compile(r"^请选择合同名称$")).get_by_role("textbox").press("Enter")
        if self.page.locator("span").filter(has_text=value).is_visible():
            self.page.locator("span").filter(has_text=value).click()

    def requestFlow(self):
        # 2.监控流程接口，获取流程接口
        # 监听请求事件
        # page.on("request", lambda request: print("request: ", request.method, request.url))
        # 监听响应事件
        # page.on("response", lambda response: print("response: ", response.status, response.url))
        # self.page.on("response", lambda response: self.seturl(response.url))
        # self.page.wait_for_timeout(2000)
        # 3.解析接口获取审批人
        # 读取cookie JSON文件
        with open(cookie_dir + "cookie.json", 'r', encoding='utf-8') as f:
            data = json.load(f)
            print(data)

        # 寻找cookie位置
        cookieInLists = data["origins"][0]["localStorage"]
        cookieIndex = 10000
        for list in cookieInLists:
            if list["name"] == "pit_token":
                cookieIndex = cookieInLists.index(list)
                break
        if cookieIndex == 10000:
            print("！！！未提取到cookie数据！！！")
        # 提取cookie数据--给接口使用（这里只是打印出来）
        cookie = cookieInLists[cookieIndex]["value"]
        print(cookie)
        # cookie后缀带|String--删除掉
        webcookie = cookie.replace("|String", "")
        head = {
            # "Accept": "application/json, text/plain, */*",
            # Add GitHub personal access token.
            "Authorization": webcookie,
        }
        # context = playwright.request.new_context(base_url='http://172.18.3.26:7300')
        httpcontext = self.playwright.request.new_context()
        response = httpcontext.get(url=self.geturl(), headers=head)
        responsejson = response.json()
        print("解析接口获取审批人:")
        print(responsejson)
        # while len(responsejson["data"]["runTask"]) != 0:
        approvalpeople = ''
        if len(httpcontext.get(url=self.geturl(), headers=head).json()["data"]["runTask"]) != 0:
            peoples = []
            peopleCount = httpcontext.get(url=self.geturl(), headers=head).json()["data"]["runTask"]
            for person in peopleCount:
                peoples.append(person["handledDtoList"][0]["handledByName"])
            # people = responsejson["data"]["runTask"][0]["handledDtoList"][0]["handledByName"]
            node = httpcontext.get(url=self.geturl(), headers=head).json()["data"]["runTask"][0]["signDeployDTO"][
                "signKeyword"]
            print("下节点审批人：" + f'{peoples}' + "   节点：" + node)
            # 4.审批人转换为账号

            if "陈凯" in peoples:
                approvalpeople = "shigong1"
                print("审批使用账户： " + approvalpeople)
            elif "谭监" in peoples:
                approvalpeople = "jianli1"
                print("审批使用账户： " + approvalpeople)
            else:

                param = {
                    "realName": peoples[0],
                }
                approvalpeople = httpcontext.get(url=url + url_getUserAcount, params=param, headers=head).json()["data"]["list"][0][
                    "username"]
                print('用户接口获取的审核账号:' + approvalpeople)
            if approvalpeople == '':
                approvalpeople = peoples[0]
                print("！！！审批人里没有找到配对人员，使用流程账号审批： " + approvalpeople)

        return approvalpeople

